const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

let is_loading = false;

Page({
  data: {
    page: 1,
    page_count: 1,
    longitude: '',
    latitude: '',
    score: [1, 2, 3, 4, 5],
    keyword: '',
    imgUrl: app.imgUrl,
  },
  onLoad(opts) {
    let that = this;
    let options = opts || {};
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
    }
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    app.pageOnLoad(this);
    let userinfo = wx.getStorageSync('user_info');
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      util.prepareBindInfo(options, moduleName, that);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 && tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
      });
    }
    that.setData({
      ids: options ? options.ids : '',
      opts: options,
    });
  },
  onShow() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.getLocation({
            success: function (res) {
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              that.loadData();
            },
            fail: function () {
              wx.navigateBack();
            },
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          wx.getLocation({
            success: function (res) {
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              that.loadData();
            },
          });
        }
      },
    });
  },
  loadData() {
    let that = this;
    let { longitude, latitude, ids } = that.data;
    wx.showLoading({
      title: '加载中',
    });
    app.ws_micro_shoprequest({
      url: api.book.shop_list,
      method: 'GET',
      data: {
        longitude,
        latitude,
        ids,
      },
      success: function (res) {
        if (res.code === 0) {
          that.setData(res.data);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      },
    });
  },
  onPullDownRefresh() {
    let that = this;
    that.setData({
      keyword: '',
      page: 1,
    });
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.getLocation({
            success: function (res) {
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              that.loadData();
            },
            fail: function () {
              wx.navigateBack();
            },
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          wx.getLocation({
            success: function (res) {
              that.setData({
                latitude: res.latitude,
                longitude: res.longitude,
              });
              that.loadData();
            },
          });
        }
      },
    });
  },
  onReachBottom() {
    if (this.data.page >= this.data.page_count) {
      return;
    }
    this.loadMoreData();
  },
  loadMoreData() {
    let that = this;
    let { page, longitude, latitude, ids } = that.data;
    if (is_loading) {
      return;
    }
    is_loading = true;
    wx.showLoading({
      title: '加载中',
    });
    app.ws_micro_shoprequest({
      url: api.book.shop_list,
      method: 'GET',
      data: {
        page,
        longitude,
        latitude,
        ids,
      },
      success: function (res) {
        if (res.code === 0) {
          let { list, page_count, row_count } = res.data;
          let shop_list = that.data.list.concat(list);
          that.setData({
            list: shop_list,
            page_count,
            row_count,
            page: (page + 1),
          });
        }
      },
      complete: function () {
        wx.hideLoading();
        is_loading = false;
      },
    });
  },
  goto(e) {
    this.location(e);
  },
  location(e) {
    let index = e.currentTarget.dataset.index;
    let shop_list = this.data.list;
    let { latitude, longitude, name, address } = shop_list[index];
    wx.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      name,
      address,
    });
  },
  inputFocus() {
    this.setData({
      show: true,
    });
  },
  inputBlur() {
    this.setData({
      show: false,
    });
  },
  inputConfirm() {
    this.search();
  },
  input(e) {
    this.setData({
      keyword: e.detail.value,
    });
  },
  search(e) {
    let that = this;
    let { keyword, longitude, latitude, ids } = that.data;
    wx.showLoading({
      title: '搜索中',
    });
    app.ws_micro_shoprequest({
      url: api.book.shop_list,
      method: 'GET',
      data: {
        keyword,
        longitude,
        latitude,
        ids,
      },
      success: function (res) {
        if (res.code === 0) {
          that.setData(res.data);
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  go(e) {
    let index = e.currentTarget.dataset.index;
    let shop_list = this.data.list;
    wx.navigateTo({
      url: '/ws_micro_shop/pages/shop-detail/shop-detail?shop_id=' + shop_list[index].id,
    });
  },
  navigatorClick(e) {
    let { open_type, url } = e.currentTarget.dataset;
    if (open_type !== 'wxapp') { return true }
    url = parseQueryString(url);
    url.path = url.path ? decodeURIComponent(url.path) : '';
    wx.navigateToMiniProgram({
      appId: url.appId,
      path: url.path,
    });
    return false;

    function parseQueryString(url) {
      let reg_url = /^[^\?]+\?([\w\W]+)$/;
      let reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g;
      let arr_url = reg_url.exec(url);
      let ret = {};
      if (arr_url && arr_url[1]) {
        let str_para = arr_url[1];
        let result;
        while ((result = reg_para.exec(str_para)) != null) {
          ret[result[1]] = result[2];
        }
      }
      return ret;
    }
  },
  onShareAppMessage() {
    let path = '/ws_micro_shop_book/pages/book/shop/shop?tabbarindex=' + app.tabbarindex + '&shopid=' + app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    return {
      path,
    };
  },
  onShareTimeline() {
    return {
      title: "",
      imageUrl: "",
      query:
        "tabbarindex=" +
        app.tabbarindex +
        "&shopid=" +
        app.ws_micro_shop_globalData.shopid,
    };
  },
  onHide() {
    util.sendBindInfo(this.data);
  },
  onUnload() {
    util.sendBindInfo(this.data);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
});
